package com.pactera.jep.service.sys.security.spring.conf;

import com.pactera.jep.service.sys.service.SecurityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsUtils;

/**
 * Spring Security配置类
 *
 * @author ghost
 */
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final static Logger logger = LoggerFactory.getLogger(WebSecurityConfiguration.class);

    @Autowired
    private WebAuthenticationSuccessHandler successHandler;

    @Autowired
    private WebAuthenticationFailureHandler failureHandler;

    @Autowired
    private SecurityService securityService;

    @Autowired
    private AuthenticationAccessDeniedHandler authenticationAccessDeniedHandler;

    @Autowired
    private MD5PasswordEncoder md5PasswordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("配置AuthenticationManagerBuilder...");
        }
        super.configure(auth);
        auth.userDetailsService(securityService).passwordEncoder(md5PasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll();
        http.authorizeRequests().anyRequest().permitAll().and().
                formLogin().loginPage("/requireLogin").loginProcessingUrl("/doLogin").usernameParameter("username")
                .passwordParameter("password").permitAll()
                // 登录失败的处理器
                .failureHandler(failureHandler)
                // 登录成功的处理器
                .successHandler(successHandler)
                .and().logout().permitAll().and().csrf().disable().exceptionHandling()
                .accessDeniedHandler(authenticationAccessDeniedHandler);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 对满足指定的url地址以及OPTIONS请求放行
        web.ignoring().antMatchers("/requireLogin").antMatchers("/v2/**/**").antMatchers("/sync");
    }

}
